import 'package:freedom/const/game_const.dart';
import 'package:freedom/page/mahjong/common/mahjong_context.dart';
import 'package:freedom/page/mahjong/common/message_content.dart';
import 'package:freedom/page/mahjong/keneck/head_image_component.dart';
import 'package:freedom/util/date_util.dart';
import 'package:freedom/util/voice_message_sound.dart';
import 'abstract_message.dart';

class ChartMessageHandler extends AbstractMessageHandler {
  @override
  void doMessage(MessageContent message) {
    if (message.bodyContent is! Map || message.messageFromUid == null) {
      return;
    }
    ChatMessage chartMessage = ChatMessage.fromJson(message.bodyContent);
    if (chartMessage.text == null) {
      return;
    }
    if (chartMessage.type == MessageTypeConst.chart) {
      HeadImageComponent? userHead =
          MahjongContext.diskAllUser[message.messageFromUid]?.head;
      if (userHead == null) {
        return;
      }
      String messageId = DateUtil.getTime(format: 'yyyyMMddHHmmssSS');
      if (chartMessage.text == null) {
        return;
      }
      int sleep = (chartMessage.text!.length * 0.3).toInt();
      MessageInfo messageInfo = MessageInfo(messageId, chartMessage.text!,
          sleep: sleep < 3 ? 3 : sleep);
      if (chartMessage.index != null && chartMessage.text != null) {
        messageInfo = MessageInfo(messageId, chartMessage.text!, sleep: 10);
        VoiceMessageSound().play("message${chartMessage.index! + 1}",
            close: () {
          // 主动退出当前消息
          userHead.exitMessage(messageId);
        });
      }
      userHead.pushMessage(messageInfo);
    } else if (chartMessage.type == MessageTypeConst.emoji) {
      var userDiskInfo =
          MahjongContext.getUserStateById(message.messageFromUid!);
      EmojiInfo emojiInfo = GameConst.emojiList
          .singleWhere((element) => element.code == chartMessage.text);
      MahjongContext.mahjongGameIndex
          .addGifMessage(userDiskInfo?.direction, emojiInfo);
    }
  }
}
